const express = require('express')
const router = express.Router()
const userDb = require('../db/user-db')
const {logI} = require('../log.js')
const {retError, retSuccess} = require('../utils/ret')
const checkType = require('../utils/checkType')
const checkToken = require('../utils/checkToken')
const checkDeviceNo = require('../utils/checkDeviceNo')
const { v4: uuidv4} = require('uuid');
const moment = require('moment')

router
    .post('/', async(req, res) => {
        let {body: {maddr,deviceNo,token,buildingUUID,role}} = req
        logI("A-S", maddr, "share_QR_Code", `${JSON.stringify(req.body)}`, "null")
        try{
            const error = checkType.shareQRCode(req.body)
            if(error){
                retError("share_QR_Code",maddr, 10001,  error.details[0].message, res);
            }else{
                let msg = {};
                msg = await checkToken(token,maddr);
                if(msg.code === 0){
                    const deviceInfo={
                        'maddr':maddr,
                        'deviceNo':deviceNo
                    }
                    let device={};
                    device = await checkDeviceNo(deviceInfo);
                    if(device.code === 0){
                        let buildingRet = {};
                        buildingRet = await userDb.selectRole(maddr,buildingUUID);
                        if(buildingRet){
                            if(buildingRet.role <= 0){
                                let ret={};
                                ret = await userDb.selectQRCodeCount(buildingUUID);
                                if(ret.count<100){
                                    const QRCodeUUID = uuidv4();
                                    await userDb.shareQRCode(maddr,buildingUUID,QRCodeUUID,role,moment().format("YYYY-MM-DD HH:mm:ss"))
                                    const retMsg = {
                                        "QRCodeUUID": QRCodeUUID
                                    }
                                    retSuccess("share_QR_Code", maddr,0, retMsg, res);
                                }else{
                                    retError("share_QR_Code", maddr,10015, 'share limit', res);
                                }
                            }else{
                                retError("share_QR_Code", maddr,10014, 'permission denied', res);
                            }
                        }else{
                            retError("share_QR_Code", maddr,10012, 'building does not exist', res);
                        }
                    }else{
                        retError("share_QR_Code", maddr,device.code, device.body, res);
                    }
                }else{
                    retError("share_QR_Code", maddr,msg.code, msg.body, res);
                }
            }
        } catch (e) {
            retError("share_QR_Code",maddr, 10001, e, res);
        }
    })
module.exports = router
